package net.jeeshop.core.smscode.impl;

import com.google.gson.JsonObject;
import com.sun.org.apache.xpath.internal.operations.Bool;
import net.jeeshop.core.smscode.ISMSCode;
import net.jeeshop.core.smscode.base.common.JSMSExample;
import net.sf.json.JSONObject;

/**
 * Created by xvhuichuang on 2017/6/29.
 */
public class SMSCodeImpl implements ISMSCode {

    private static String resultId = null;
    private static ISMSCode sISMSCode = null;

    private SMSCodeImpl(){}

    public synchronized static ISMSCode getInstance(){
        if (sISMSCode == null) {
            sISMSCode = new SMSCodeImpl();
        }
        return sISMSCode;
    }

    @Override
    public boolean sendSMSCode(String phone) {
        String result = JSMSExample.testSendSMSCode(phone);
        if (result == null) return false;
        String info = getSendResultInfo(result);
        if (info == null) return false;
        this.resultId = info;
        return true;
    }

    @Override
    public boolean validSMSCode(String code) {
        if (resultId == null) return false;
        String result = JSMSExample.testSendValidSMSCode(resultId, code);
        if (result == null) return false;
        return getValidResultInfo(result);
    }

    private String getSendResultInfo(String result){
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        String info = jsonObject.getString("error");
        if (info != null){
            return null;
        }
        info = jsonObject.getString("msg_id");
        if (info == null){
            return null;
        }
        return info;
    }

    private boolean getValidResultInfo(String result){
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
        Boolean info = jsonObject.getBoolean("is_valid");
        if (info) return true;
        return false;
    }

}
